package com.example.spider.provider.speedTest;

import cn.hutool.core.util.ReUtil;
import com.example.spider.task.AbstractSpiderTask;
import com.example.spider.task.SpiderResultHandler;
import com.example.spider.util.FileBasedCollection;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * 处理详情页结果
 *
 * @author anonymous
 */
@Slf4j
@Component
public class SpeedTestDetailHandler implements SpiderResultHandler<SpeedTestDetailHandler.SpeedTestDetailTask, String> {


    @Autowired
    @Qualifier("test_url_set")
    public FileBasedCollection<ConcurrentSkipListSet<String>, String> list;

    /**
     * handle
     */
    @Override
    public void handle(SpeedTestDetailTask task, String html) {
        log.debug("prepare handing {} {} ", task.getClass().getSimpleName(), task.getUrl());
        // 全是二次跳转，无法测试匹配
        String regex = "<div class=\"vod\">.*?<a href=\"(/video/.*?.html)\">.*?data-original=\"(.*?)\".*?<a href=\"/video/(.*?).html\">(.*?)</a>";
        List<String> l = ReUtil.findAll(regex, html, 2);

        log.error(task.getTitle() + "  cost=" + task.getRequestCost() + "   url = " + task.getUrl() + "  match=" + (l.size() > 0));

        list.add(task.getRequestCost() + "\t" + task.getTitle() + "\t" + task.getUrl() + "\t" + l.size());

        log.info("finished handle {} {}", task.getClass().getSimpleName(), task.getUrl());

    }

    @Getter
    @Setter
    @Accessors(chain = true)
    public static class SpeedTestDetailTask extends AbstractSpiderTask<String> {

        private String title;

    }
}
